/*
 * Delay.java
 *
 * Created on June 3, 2007, 4:58 PM
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package base;

import tal.drivechain.plugin.Module;
import tal.drivechain.variable.Variable;
import tal.drivechain.matchers.VarMatcher;
import tal.drivechain.plugin.Channel;
import tal.drivechain.variable.SetProperty;
import tal.drivechain.variable.VarTableAction;
        
/**
 *
 * @author Main
 */
public class Delay extends Module{
    VarMatcher trigger = null;
    Variable delay = null;
    VarTableAction setDelay;
    
    public void setupProperties() {
        setTrigger(props.getProperty("trigger"), null);
        setDelay(props.getProperty("delay"), null);
    }

    public void setTrigger(Object value, SetProperty.Flag flag) {
        trigger = (VarMatcher)value;
    } public Object getTrigger() { return trigger; }
    
    public void setDelay(Object value, SetProperty.Flag flag) {
        delay = (Variable)value;
        setDelay = new VarTableAction(delay.getName(), VarTableAction.Action.SET_ANY);
        setDelay.set(delay, localVars, this);
    } public Object getDelay() { return delay; }
    
    @Override
    protected void msgReceived(Variable in, long timestamp, Channel channel) {
        if (trigger.matches(in, channel, this)) {
            long delayms = (Long)delay.getValue(this);
            if (infoFlag) log("Will fire " + in.toString(this) + " in " + delayms + "ms.", MSG.INFO);
            if (delayms!=0)
                new SendThread(delayms, in, this).start();
            else sendToOutputs(in, -1);
        }
    }
    
    class SendThread extends Thread {
        private long delay;
        private Variable out;
        private Delay plug;
        
        public SendThread(long delay, Variable out, Delay plug) {
            this.delay = delay;
            this.out = out.copyVar();
            this.plug = plug;
        }
        
        @Override
        public void run() {
            synchronized(this) {
                try {
                    this.wait(delay);
                } catch (InterruptedException ie) { return; }
            }
            plug.sendToOutputs(out, -1);
        }
    }
}
